﻿//引用
using Microsoft.AspNetCore.Mvc;     //nlog引用
using Microsoft.Extensions.Logging; //nlog引用
using OAProject.Domain.Entities;
using OAProject.Domain.Interfaces;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using OAProject.API.Models;
using Microsoft.AspNetCore.Authorization;
using OAProject.API.JWT;
using System.Collections.Generic;

namespace OAProject.API.Controllers
{
    /// <summary>
    /// 用户Api控制器
    /// </summary>
    [Route("api/[controller]/[Action]")]
    [ApiController]
    //[Authorize]     //全局授权过滤器
    public class UsersAPIController : ControllerBase
    {
        //依赖注入
        private IUsersRepository _repository;
        private IMenusRepository _Menus;                          //菜单
        private IUsersMenusRepository _UsersMenus;               //用户菜单
        private INLogRepository _nLogRepository;               //日志表
        
        private readonly ILogger<UsersAPIController> _logger;   //nlog依赖注入
        private readonly ITokenHelper _tokenHelper;             //Jwt
        public UsersAPIController(IUsersRepository repository, IMenusRepository Menus, IUsersMenusRepository UsersMenus, ILogger<UsersAPIController> logger, INLogRepository nLogRepository, ITokenHelper tokenHelper)
        {
            _repository = repository;
            _Menus = Menus;
            _UsersMenus = UsersMenus;
            _logger = logger;       //日志
            _nLogRepository = nLogRepository;
            _tokenHelper = tokenHelper; //Jwt

         //   _departmentsRepository = departmentsRepository;//组织
         //   _usersDeparRepository = usersDeparRepository;  //用户组织显示表
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="log"></param>
        /// <param name="name"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Login([FromForm] Users obj, [FromForm] LogMessage log)
        {
            try
            {
                var res = new ResponseModel();

                if (string.IsNullOrWhiteSpace(obj.LoginName) || string.IsNullOrWhiteSpace(obj.Pwd))
                {
                    res.Code = 400;
                    res.Msg = "用户名密码不能为空";
                    return BadRequest(res);
                }

                var result = _repository.Login(obj);
                ////用户id存入redis
                Common.RedisHelper.Set("Userid", result.UserID);
                int i = result != null ? 1 : 0;
                if (i != 0)
                {
                    Dictionary<string, string> keyValuePairs = new Dictionary<string, string>
                    {
                        { "LoginName", obj.LoginName }
                    };

                    //MD5加密
                    //obj.Pwd = SecurityHelper.Md5Security(obj.Pwd);

                    res.Code = 200;
                    res.Msg = "登录成功";

                    //（2） 后端：帮助类来生成JWT字符串，JWT字符串返回给浏览器
                    res.TnToken = _tokenHelper.CreateToken(keyValuePairs);

                    _logger.LogError($"HI--{obj.LoginName}--{DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss")}");   //记录日志

                    //保存到日志
                    //添加日志
                    log.IpAddress = GetClientInternetIPAddress2();  //获取本机公网IP地址 
                    log.OperationName = obj.LoginName;  //操作人
                    log.OperationTime = DateTime.Now;       //当前时间
                    log.LogInfo = $"HI--{obj.LoginName}--{DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss")},操作了";       //日志输出
                    log.StackTrace = $"你操作了UsersAPIController控制器里的Login方法"; //跟踪
                    LogAdd(log);
                    

                    return Ok(res);

                }
                else
                {
                    res.Code = 401;
                    res.Msg = "用户名或密码不正确";
                    return Unauthorized(res);  //401的错误码
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 显示+查询+分页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetShow(int parentID = 0, string username = "", int page = 1, int limit = 10)
        {
            if (username != null)
            {
                List<Users> users = _repository.Show().Where(x => x.UserName.Contains(username)).ToList();
                var list = users.Skip((page - 1) * limit).Take(limit).ToList();
                return Ok(new
                {
                    data = list,
                    code = 0,
                    msg = "",
                    count = users.Count
                });
            }
            else
            {
                List<Users> lst = _repository.Show();
                var list = lst.Skip((page - 1) * limit).Take(limit).ToList();
                return Ok(new { code = 0, data = list, count = lst.Count });
            }

        }

        /// <summary>
        /// 用户表删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Delete(int id)
        {
            var n = _repository.Delete(id);

            return Ok(new
            {
                data = n
            });
        }

        /// <summary>
        /// 用户的添加
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromForm] Users obj)   //[FromForm]是接受页面传过来的数据
        {
            obj.CreateDate = DateTime.Now;  //创建时间
            int a = _repository.Insert(obj);
            return Ok(a);
        }

        /// <summary>
        /// 用户的反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Fantian(int id)
        {
            var list = _repository.GetById(id);
            return Ok(new
            {
                data = list
            });
        }

        /// <summary>
        /// 用户的修改
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Update([FromForm] Users obj)
        {
            obj.CreateDate = DateTime.Now;
            var list = _repository.Update(obj);
            return Ok(list);
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdatePwd(int userID)
        {
            var list = _repository.GetById(userID);

            list.Pwd = "123456";
            list.CreateDate = DateTime.Now;
            int result = _repository.Update(list);
            return Ok(result);
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UptStatus(int userID)
        {
            var list = _repository.GetById(userID);

            list.Status = false;
            list.CreateDate = DateTime.Now;
            int result = _repository.Update(list);
            return Ok(result);
        }

        /// <summary>
        /// 忘记密码
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="loginName"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ForgetPwd([FromForm] string loginName, [FromForm] string pwd)
        {
            var list = _repository.ForgetPwd(loginName);
            list.Pwd = pwd;
            int result = _repository.Update(list);
            return Ok(result);

        }

        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult LogAdd([FromForm] LogMessage obj)
        {
            var a = _nLogRepository.Insert(obj);
            return Ok(a);
        }

        /// <summary>  
        /// 获取本机公网IP地址  
        /// </summary>  
        /// 获取一些ip、硬盘序号连接(https://www.cnblogs.com/zouhao/p/7324978.html)拿过来直接用  需要引用一些东西  下载NuGet包
        /// <returns>本机公网IP地址</returns>  
        [HttpGet]
        private static string GetClientInternetIPAddress2()
        {
            string tempip = "";
            try
            {
                //http://iframe.ip138.com/ic.asp 返回的是：您的IP是：[220.231.17.99] 来自：北京市 光环新网  
                WebRequest wr = WebRequest.Create("http://iframe.ip138.com/ic.asp");
                Stream s = wr.GetResponse().GetResponseStream();
                StreamReader sr = new StreamReader(s, Encoding.Default);
                string all = sr.ReadToEnd(); //读取网站的数据  

                int start = all.IndexOf("[") + 1;
                int end = all.IndexOf("]", start);
                tempip = all.Substring(start, end - start);
                sr.Close();
                s.Close();
                return tempip;
            }
            catch
            {
                return "unknown";
            }
        }

        #region 树形（递归）
        /// <summary>
        /// 父类的哈希表(递归)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Shu(int parentID = 0)
        {
            List<Menus> menus = _Menus.Show();
            List<Menus> menus1 = menus.Where(x => x.ParentID.Equals(parentID)).ToList();

            GetShow(parentID);

            List<Dictionary<string, object>> data = new List<Dictionary<string, object>>();
            foreach (var item in menus1)
            {
                Dictionary<string, object> json = new Dictionary<string, object>();
                json.Add("id", item.MenuID);
                json.Add("title", item.MenuName);
                json.Add("spread", true);
                Shu_nest(menus, json, item.MenuID);
                data.Add(json);
            }
            return Ok(data);
        }
        

        /// <summary>
        /// 子类
        /// </summary>
        /// <param name="menus"></param>
        /// <param name="json"></param>
        /// <param name="menuID"></param>
        private void Shu_nest(List<Menus> menus, Dictionary<string, object> json, int menuID)
        {
            List<Menus> menus1 = menus.Where(x => x.ParentID.Equals(menuID)).ToList();
            List<Dictionary<string, object>> data = new List<Dictionary<string, object>>();
            if (menus1.Count == 0)
            {
                json.Add("children", null);
                return;
            }
            foreach (var item in menus1)
            {
                Dictionary<string, object> json1 = new Dictionary<string, object>();
                json1.Add("id", item.MenuID);
                json1.Add("title", item.MenuName);
                json1.Add("spread", true);
                Shu_nest(menus, json1, item.MenuID);
                data.Add(json1);
            }
            json.Add("children", data);
        }
        

        /// <summary>
        /// 拼接字符串的树
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ShuShow(int id)
        {
            List<RoleMenus> m = _UsersMenus.RoleMenusShow(id);
            List<int> ids = m.Where(x => x.MenuID1 != 0).Select(y => y.MenuID).ToList();
            return Ok(new
            {
                data = m,
                code = 0,
                msg = "",
                checkedId = ids
            });
        }

        /// <summary>
        /// 修改分配权限
        /// </summary>
        /// <param name="menuIds"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddRoleMenus([FromForm] List<int> menuIds, [FromForm] int userId)
        {
            var list = _UsersMenus.AddRoleMenus(menuIds, userId);
            return Ok(list);
        }
        #endregion

    }
}
